import TauActionPanel from '@/components/TauActionPanel';
import TauPage from '@/components/TauPage';
import { t } from '@lingui/macro';
import { Message, Tab, Button, Drawer, Dialog } from '@alifd/next';
import React, { useEffect, useRef, useState } from 'react';
import { ENUMS, column, toSelectDataSource } from './stores/definitions';
import { useStore } from '@/hooks';
// import TauTable from '@/components/TauTable';
import { uniqueId } from 'lodash';
import { observer } from 'mobx-react-lite';
import TauTable from '@/components/TauTable';
import TicketTable from './components/TicketTable';
import { toJS } from 'mobx';
import DetailDrawer from './components/DetailDrawer';
import RefundPrice from './components/refund/RefundPrice';
import moment from 'moment';
import MoreFuncDropDown from '@/components/MoreFuncDropDown';
import { areArraysEqual, arrayContrast } from './stores/method';
import ComponentsDrawer from '@/components/Drawers/ComponentsDrawer';
import useDebounce from '@/hooks/useDebounce';

const tableId = uniqueId('tuaTable-');

const tabItems = [
  { key: '5', label: t`全部订单` },
  { key: '4', label: t`退款记录` },
];

const formatArea = (stations) => {
  const tmp = _.cloneDeep(stations?.selectedPath) || [];
  let res = [];
  if (tmp.length <= 0) return res;
  res = tmp.reduce((result, cur) => {
    result.push(cur.value);
    return result;
  }, []);
  return res;
};

function ScOrder({ filter, hideActions, hiddenSearchItems = [], queryParams }) {
  const [modal, setModal] = useState([]);
  const [expandAll, setExpandAll] = useState(false);
  const { rsOrderStore: store } = useStore();
  const orderRef = useRef();

  useEffect(() => {
    store.search = {
      ...filter,
      ...queryParams,
    };
    if (queryParams) {
      store.isView = true;
    }
    return (() => {
      store._orderStatus = '5';
      store.orders = [];
    });
  }, []);

  // 获取列表数据
  const handleOnSearch = (params) => {
    const { orderDate, getOnDate, startStations: d1, endStations: d2, ...searchArgs } = params.values;
    const [from, to] = orderDate || [];
    if (store._orderStatus !== '4') {
      const [fromTime, toTime] = getOnDate || [];
      const { endStations, startStations } = params?.valueObjects || {};
      const [startMainArea, ...startMinorAreas] = formatArea(startStations || {});
      const [endMainArea, ...endMinorAreas] = formatArea(endStations || {});
      store.search = {
        ...filter,
        ...queryParams,
        from,
        to,
        fromTime,
        toTime,
        startMainArea,
        startMinorAreas: [...startMinorAreas],
        endMainArea,
        endMinorAreas: [...endMinorAreas],
        ...searchArgs,
      };
    } else {
      store.search = {
        ...searchArgs,
      };
    }
  };

  // 点击打开查看
  const handleView = (order) => {
    orderRef.current = order;
    setModal(['view']);
  };

  // 点击打开编辑
  const handleEdit = (order) => {
    orderRef.current = order;
    setModal(['edit']);
  };

  // Modal窗口关闭回调
  const handleCancel = () => {
    setModal([]);
  };

  // 变更数据提交
  const handleUpdate = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        await store.update(result);
        Message.success({ content: t`修改成功` });
      } catch (error) {
        Message.error({ content: t`修改失败`, duration: 7000 });
        throw error;
      }
    }
    setModal([]);
  };

  // 点击打开退款
  const handleRefund = (order) => {
    orderRef.current = order;
    setModal(['refund']);
  };

  // 发起退款
  const handleOnRefund = useDebounce(async (result, state, type, account, otherAccount, open, accountSp) => {
    if (!_.isEmpty(result)) {
      try {
        let refundArgs = {};
        let args = {};
        const { id, cancelTime, refundPrice, distanceTime, cancelRemark = '', orderDetails, attachments, enableProfitShare, cancelOrder, cancelCoupon } = toJS(result);
        const utcTime = moment.utc(cancelTime).subtract('8', 'hour').toISOString();
        /**
         * 退款逻辑 (退票和其他退款)
         * 1. 没有操作分账金额就给分账参数后端
         * 2. 页面上已经减去的退款金额要还原给后端
         * 3. 分账金额统一已 分 为单位
         */
        if (store._orderRefundStatus === '0') {
          const numberAccount = account.map((item) => ({
            ...item,
            contributionAmount: Number(item.contributionAmount),
          }));
          const computeAccount = arrayContrast(open, store.accounts, account);
          const equal = areArraysEqual(store.initAccounts, numberAccount);
          const orderTicket = orderDetails?.filter((item) => item.checked && !item.disabled);
          const newOrderTicket = orderTicket.map((item) => ({
            ...item,
            originalPrice: item.ticketPrice,
          }));
          refundArgs = {
            cancelTime: utcTime,
            refundPrice: Number(refundPrice),
            distanceTime,
            cancelRemark,
            attachments: attachments || [],
            ticketRefundInfos: newOrderTicket,
            state,
            type,
            cancelCoupon,
            orderInfo: {
              orderId: id,
              directRoute: false,
              suborderId: id,
            },
          };
          /**
           * https://pm.aspiretop.com/issues/3179
           */
          if (!equal) {
            refundArgs.refundPayers = computeAccount;
          }
          args = {
            enableProfitShare,
            cancelOrder,
            report: true,
          };
        } else if (store._orderRefundStatus === '1') {
          const numberAccount = otherAccount.map((item) => ({
            ...item,
            contributionAmount: Number(item.contributionAmount),
          }));
          const computeAccount = arrayContrast(open, store.accounts, otherAccount);
          const equal = areArraysEqual(store.initAccounts, numberAccount);
          refundArgs = {
            cancelTime: utcTime,
            refundPrice: Number(refundPrice),
            distanceTime,
            cancelRemark,
            attachments: attachments || [],
            state,
            type,
            orderInfo: {
              orderId: id,
              directRoute: false,
              suborderId: id,
            },
          };
          /**
           * https://pm.aspiretop.com/issues/3179
           */
          if (!equal) {
            refundArgs.refundPayers = computeAccount;
          }
          args = {
            enableProfitShare,
            cancelOrder,
            report: true,
          };
        } else {
          // 投诉索赔参数
          const _account = _.cloneDeep(accountSp);
          const distributeInfos = [];
          for (let i = 0; i < _account.length; i++) {
            const { check, contributionAmount = 0, targetId, targetName, targetType } = _account[i];
            if (check) {
              distributeInfos.push({
                amount: contributionAmount * 100,
                targetId,
                targetName,
                targetType,
              });
            }
          }
          _.assign(args, {
            orderId: id,
            reason: cancelRemark,
            attachments: attachments || [],
            distributeInfos,
          });
        }
        if (store._orderRefundStatus === '0' || store._orderRefundStatus === '1') {
          await store.orderSponsorRefund(id, refundArgs, args);
        } else {
          // 线下支付 投诉索赔
          await store.orderCreateOffline(args);
        }
        Message.success({ content: t`退款申请成功` });
      } catch (e) {
        Message.error({ content: t`退款申请失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  }, 200);

  const handleTableAction = (info, action) => {
    switch (action) {
      case 'view':
        handleView(info);
        break;
      case 'edit':
        handleEdit(info);
        break;
      case 'refund':
        handleRefund(info);
        break;
      case 'customerForm':
        handleOpenCustomer(info);
        break;
      default:
        break;
    }
  };

  const handleOpenCustomer = (order) => {
    orderRef.current = order;
    setModal(['customerForm']);
  };


  const handleCancelOrder = (result) => {
    Dialog.confirm({
      content: t`是否取消订单？`,
      onOk: async () => {
        try {
          const { id } = toJS(result);
          await store.orderCancel({ orderId: id });
          Message.success({ content: t`成功取消订单` });
        } catch (error) {
          Message.error({ content: t`取消订单失败`, duration: 5000 });
          throw error;
        }
      },
    });
  };

  const handleOrderEnableShare = (result) => {
    Dialog.confirm({
      content: t`是否开启分账？`,
      onOk: async () => {
        try {
          const { id } = toJS(result);
          await store.orderEnableShare({ orderId: id });
          Message.success({ content: t`成功开启分账` });
        } catch (error) {
          Message.error({ content: t`开启分账失败`, duration: 5000 });
          throw error;
        }
      },
    });
  };


  return (
    <TauPage className="page-container">
      <TauActionPanel
        onSearch={handleOnSearch}
        actions={hideActions ? [] : [
          {
            name: 'btn-syncStatus',
            title: t`同步最近状态`,
            type: 'primary',
            onClick: async () => {
              await store.sync();
              Message.success({ content: t`同步成功` });
            },
          },
        ]}
        searchItems={store._orderStatus === '4' ?
          [
            {
              name: 'orderDate',
              type: 'date-range',
              props: {
                placeholder: [t`退款起始时间`, t`退款结束时间`],
              },
            },
            {
              name: 'state',
              type: 'select',
              props: {
                dataSource: toSelectDataSource(ENUMS.state),
                placeholder: t`申请状态`,
              },
            },
            {
              name: 'type',
              type: 'select',
              props: {
                dataSource: toSelectDataSource(ENUMS.refundType),
                placeholder: t`退款类型`,
              },
            },
          ] : [
            {
              name: 'orderDate',
              type: 'date-range',
              props: {
                placeholder: [t`起始订单时间`, t`结束订单时间`],
              },
            },
            {
              name: 'ticketState',
              type: 'select',
              props: {
                dataSource: toSelectDataSource(ENUMS.ticketStatus),
                placeholder: t`车票状态`,
              },
            },
            {
              name: 'getOnDate',
              type: 'date-range',
              props: {
                placeholder: [t`起始上车时间`, t`结束上车时间`],
              },
            },
            {
              name: 'startStations',
              type: 'sc-station',
              props: {
                placeholder: t`始发站点`,
                style: { minWidth: '160px' },
              },
            },
            {
              name: 'endStations',
              type: 'sc-station',
              props: { placeholder: t`结束站点`, style: { minWidth: '160px' } },
            },
          ].filter((si) => hiddenSearchItems.indexOf(si.name) === -1)}
        keywordSearch={{
          placeholder: t`请输入关键字搜搜`,
        }}
        className="action-panel"
      />
      <div className="content">
        <Tab
          defaultActiveKey={'5'}
          accessKey={store.orderStatus}
          onChange={(v) => {
            store.orderStatus = v;
            store.orders = [];
          }}
          extra={
            store._orderStatus !== '4' &&
            <Button
              type="primary"
              onClick={() => setExpandAll(!expandAll)}
            >
              {expandAll ? t`合并全部` : t`展开全部`}
            </Button>
          }
        >
          {tabItems.map((item) => (<Tab.Item key={item.key} title={item.label} />))}
        </Tab>
        {store._orderStatus === '4' ?
          <TauTable
            instanceId={tableId}
            primaryKey="refundNumber"
            tableLayout="fixed"
            currentPage={store.pg.page}
            pageSize={store.pg.size}
            total={store.total}
            sort={store.tableSort}
            onFetch={(pg) => { store.pg = pg; }}
            loading={store.loading}
            expandedRowIndent={[300, 100]}
            expandAll={expandAll}
            dataSource={toJS(store.orders)}
            columns={[
              { title: t`编号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
              column('orderInfo.orderId', {
                width: 200,
                cell: (v, _, order) => {
                  return <Button text type="primary" onClick={() => handleTableAction(order, 'view')}>{v}</Button>;
                },
              }),
              column('applicationId', { width: 180 }),
              column('orderInfo.name', { width: 98 }),
              column('type', { width: 138 }),
              column('rsOrder.orderStatus', { width: 118 }),
              column('cancelTime', { width: 180 }),
              column('refundTime', { width: 180 }),
              column('refundPrice', { width: 118 }),
              column('cancelRemark', { width: 200 }),
            ].filter((c) => c.dataIndex !== 'action' || !hideActions)}
          /> :
          <TauTable
            instanceId={tableId}
            primaryKey="orderNumber"
            tableLayout="fixed"
            currentPage={store.pg.page}
            pageSize={store.pg.size}
            total={store.total}
            sort={store.tableSort}
            onFetch={(pg) => { store.pg = pg; }}
            loading={store.loading}
            expandedRowRender={(row) => (
              <TicketTable
                rsOrder={row.rsOrder}
                refundInfo={row.applicationRefunds}
              />
            )}
            expandedRowIndent={[300, 100]}
            expandAll={expandAll}
            dataSource={toJS(store.orders)}
            columns={[
              { title: t`编号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
              column('orderNumber', {
                width: 200,
                cell: (v, _, order) => {
                  return <Button text type="primary" onClick={() => handleTableAction(order, 'view')}>{v}</Button>;
                },
              }),
              column('rsOrder.stationText', {
                width: 110,
              }),
              column('rsOrder.subscribeName', {
                width: 58,
                cell: (v, i, r) => <Button type="primary" text onClick={() => handleTableAction(r, 'customerForm')}>{v}</Button>,
              }),
              column('companyName', { width: 58 }),
              column('price', { width: 118 }),
              column('rsOrder.orderStatus', { width: 58 }),
              column('sourceGroup', { width: 200 }),
              column('crDate', { width: 124, sortable: true }),
              column('rsOrder.predictBeginDate', { width: 124, sortable: true }),
            ].concat((store._orderStatus === '5') ?
              [
                {
                  title: t`操作`,
                  dataIndex: 'action',
                  width: 120,
                  cell: (_, __, order) => {
                    const { enableProfitShare, rsOrder } = order;
                    const { orderStatus } = rsOrder || {};
                    const funcMenu = [
                      {
                        title: '编辑',
                        onClick: () => handleTableAction(order, 'edit'),
                      },
                      {
                        title: '退款',
                        onClick: () => handleTableAction(order, 'refund'),
                      },
                      {
                        title: t`取消订单`,
                        onClick: () => handleCancelOrder(order),
                        show: orderStatus !== 0 && orderStatus !== 3,
                      },
                      {
                        title: t`开启分账`,
                        onClick: () => handleOrderEnableShare(order),
                        show: !enableProfitShare,
                      },
                    ];
                    return (
                      <>
                        <MoreFuncDropDown
                          dropdownItems={funcMenu}
                          maxShow={1}
                        />
                      </>
                    );
                  },
                },
              ] : []).filter((c) => c.dataIndex !== 'action' || !hideActions)}
          />}
      </div>
      <DetailDrawer
        modal={modal}
        handleCancel={handleCancel}
        handleUpdate={handleUpdate}
        orderId={orderRef.current?.orderNumber || orderRef.current?.orderInfo?.orderId}
        visible={modal[0] === 'view' || modal[0] === 'edit'}
        onClose={() => {
          setModal([...modal, `toClose$${Date.now()}`]);
          handleCancel();
        }}
      />
      <Drawer
        visible={modal[0] === 'refund'}
        title={t`申请退款`}
        onClose={() => setModal([...modal, `toClose$${Date.now()}`])}
        closeMode={['esc', 'mask', 'close']}
        style={{ maxWidth: '90%' }}
        width="80%"
      >
        <RefundPrice modal={modal} order={orderRef.current} onCancel={handleCancel} onSubmit={handleOnRefund} />
      </Drawer>
      <ComponentsDrawer modal={modal} queryParams={{ username: orderRef.current?.username }} name={orderRef.current?.rsOrder?.subscribeName} onCancel={handleCancel} />
    </TauPage>
  );
}
export default observer(ScOrder);
